#pragma once
/**
 * @file json_utils.h
 * @brief JSON utility functions for configuration handling
 */

#ifndef HFT_SYSTEM_UTILS_JSON_UTILS_H
#define HFT_SYSTEM_UTILS_JSON_UTILS_H

#include "nlohmann/json.hpp"
#include <string>
#include <fstream>
#include <stdexcept>

namespace utils {

class JsonUtils {
public:
    /**
     * @brief Load JSON configuration from file
     * @param filepath Path to the JSON file
     * @return Parsed JSON object
     * @throw std::runtime_error If file cannot be opened or parsed
     */
    static nlohmann::json loadFromFile(const std::string& filepath);

    /**
     * @brief Save JSON object to file
     * @param filepath Path to save the JSON file
     * @param j JSON object to save
     * @throw std::runtime_error If file cannot be created
     */
    static void saveToFile(const std::string& filepath, const nlohmann::json& j);

    /**
     * @brief Get value from JSON object with default
     * @tparam T Type of the value to retrieve
     * @param j JSON object
     * @param key Key to look up
     * @param defaultValue Default value if key not found
     * @return Retrieved value or defaultValue
     */
    template<typename T>
    static T getValue(const nlohmann::json& j, const std::string& key, const T& defaultValue) {
        return j.value(key, defaultValue);
    }
};

} // namespace utils

#endif // JSON_UTILS_H


#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <stdexcept>
#include <nlohmann/json.hpp>

// 使用nlohmann/json库
using json = nlohmann::json;

// JSON工具类
class JsonUtils {
public:
    // 从文件加载JSON
    static json load_from_file(const std::string& file_path) {
        std::ifstream file(file_path);
        if (!file.is_open()) {
            throw std::runtime_error("Failed to open JSON file: " + file_path);
        }
        
        json j;
        file >> j;
        return j;
    }
    
    // 保存JSON到文件
    static void save_to_file(const json& j, const std::string& file_path) {
        std::ofstream file(file_path);
        if (!file.is_open()) {
            throw std::runtime_error("Failed to open JSON file for writing: " + file_path);
        }
        
        file << j.dump(4);  // 使用4个空格缩进
    }
    
    // 获取JSON值，如果不存在则返回默认值
    template<typename T>
    static T get_value(const json& j, const std::string& key, const T& default_value) {
        if (j.contains(key)) {
            return j[key].get<T>();
        }
        return default_value;
    }
    
    // 检查JSON是否包含指定的键
    static bool has_key(const json& j, const std::string& key) {
        return j.contains(key);
    }
};